package com.gitee.yannzh.rune.dao.mp.handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * @author Yann
 * @Date 2019/10/8
 * Mybatis plus 自动填充配置类
 */
@Slf4j
public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {

    private static final String CREATE_TIME = "createTime";
    private static final String CREATE_BY = "createBy";
    private static final String UPDATE_TIME = "updateTime";
    private static final String UPDATE_BY = "updateBy";
    private static final String IS_DELETED = "deleted";
    private static final String VERSION = "version";


    @Override
    public void insertFill(MetaObject metaObject) {
        if (ObjectUtil.isNotNull(metaObject)) {
            this.setFieldValByName(CREATE_TIME, LocalDateTime.now(), metaObject);
            this.setFieldValByName(IS_DELETED, 0L, metaObject);
            this.setFieldValByName(VERSION, 0, metaObject);
            this.setFieldValByName(CREATE_BY, getLoginUser(), metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (ObjectUtil.isNotNull(metaObject)) {
            this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
            this.setFieldValByName(UPDATE_BY, getLoginUser(), metaObject);
        }

    }

    private Long getLoginUser() {
        try {
            return 0L;
        } catch (Exception e) {
            return -1L;
        }
    }
}
